package intranet.controllers;
import org.apache.jasper.tagplugins.jstl.core.ForEach;
import org.apache.jasper.tagplugins.jstl.core.Redirect;
import org.eclipse.jdt.internal.compiler.ast.ForeachStatement;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.ModelAndView;
import intranet.models.*;
import intranet.tools.*;
import java.io.IOException;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class CommentController extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@SuppressWarnings("null")
	public CommentController(){
		//HttpServletRequest request = null;
		//ModelAndView mv=new ModelAndView("index");
		//if (request.getSession().getAttribute("session")==""){
			//response.sendRedirect("Login.html");
		//}
	}
	
	/* IsNumber Function */
	public static boolean IsNumber(String num) {
        try {
            Integer.parseInt(num);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
	
	@RequestMapping("wall_comment.html")
	public ModelAndView Walls(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException,ServletException, IOException{
		ModelAndView mv=new ModelAndView("index");
		if(session.getAttribute("user_id")!=null){
			CommentModel Comment=new CommentModel();
			ResultSet rswalls=Comment.SelectWall(0);
			ArrayList arrwalls=this.resultSetToArrayList(rswalls);
		
			// Passing Page Included
			mv.addObject("includethispage", "wall_comment/wall.jsp");
			// Passing Most Viewed & Other Videos
			mv.addObject("walls", arrwalls);
		}else{
			response.sendRedirect("login.html");
		}
		return mv;
	}
	
	@RequestMapping("view_wall.html")
	public ModelAndView ViewWall(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException,ServletException, IOException{
		ModelAndView mv=new ModelAndView("index");
		HTMLWriter htmlwriter=new HTMLWriter();
		if(session.getAttribute("user_id")!=null){	
			CommentModel Comment=new CommentModel();
			int wall_id=(IsNumber(request.getParameter("wall_id"))?Integer.parseInt(request.getParameter("wall_id")):0);
			
			ResultSet rswalls=Comment.SelectWall(wall_id);
			ArrayList arrwalls=this.resultSetToArrayList(rswalls);
			
			ResultSet rsposts=Comment.SelectWallItem(wall_id);
			ArrayList arrposts=this.resultSetToArrayList(rsposts);
		
			// Passing Page Included
			mv.addObject("includethispage", "wall_comment/wall_posting.jsp");
			
			// Passing Walls
			mv.addObject("walls", arrwalls);
			// Passing Posts
			mv.addObject("posts", arrposts);
			
			
			/* Select last 2 comments of each topic */
			ResultSet rstcom=null;
			ResultSet rstuser=null;
			String username="";
			String [] comments=new String[arrposts.size()];
			int [] counts=new int[arrposts.size()];
			int j=0;
			//Declare one more resultSet for items selected in a specified wall
			rsposts.beforeFirst();
			while(rsposts.next()){
				rstcom=Comment.SelectComment(rsposts.getInt("ITEM_ID"));
				ArrayList arrcom=this.resultSetToArrayList(rstcom);
				/* Number of comments in each items */
				counts[j]=arrcom.size();
				int i=0;
				comments[j]="";
				rstcom.beforeFirst();
				while(rstcom.next()){
					//if(i>=(arrcom.size()-2)){
						String removeme="";
						rstuser=Comment.SelectUser(rstcom.getInt("USER_POST"));
						while(rstuser.next()){
							username=rstuser.getString("USER_NAME");
						}
						if(username.equals(session.getAttribute("user_name").toString())){
							removeme="&nbsp;&nbsp;<label class=\"commentlink\" onclick=\"delete_comment.html?com_id="+rstcom.getString("COMMENT_ID")+"&wall_id="+wall_id+"\">Remove</label>";
						}
						comments[j]+="<p class=\"comment\" align=\"justify\"><label class=\"userpost\">"+username+"&nbsp;</label>";
						comments[j]+=htmlwriter.escapeHTML(rstcom.getString("COMMENT_DESC"))+"<br><br><label class=\"eventtext\">"+rstcom.getString("DATE_POST")+"</label>"+removeme+"</p>";
					//}
					//i++;
				}
				j++;
			}
			mv.addObject("comments", comments);
			mv.addObject("counts", counts);
		
		}else{
			response.sendRedirect("login.html");
		}
		return mv;
	}

	@RequestMapping("new_topic.html")
	public void InsertTopic(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException,ServletException, IOException{
		if(session.getAttribute("user_id")!=null){	
			int wall_id=Integer.parseInt(request.getParameter("wallid"));
			String item_desc=request.getParameter("itemdesc");
			CommentModel comment=new CommentModel();
			if(item_desc!=""){
				comment.InsertNewItem(wall_id, item_desc,Integer.parseInt(session.getAttribute("user_id").toString()));
			}
			response.sendRedirect("view_wall.html?wall_id="+wall_id);
		}else{
			response.sendRedirect("login.html");
		}
	}
	
	@RequestMapping("delete_comment.html")
	public void DeleteComment(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException,ServletException, IOException{
		if(session.getAttribute("user_id")!=null){	
			int wall_id=Integer.parseInt(request.getParameter("wall_id"));
			int com_id=Integer.parseInt(request.getParameter("com_id"));
			CommentModel comment=new CommentModel();
			comment.DeleteComment(com_id,Integer.parseInt(session.getAttribute("user_id").toString()));
			response.sendRedirect("view_wall.html?wall_id="+wall_id);
		}else{
			response.sendRedirect("login.html");
		}
	}
	
	@RequestMapping(value="add_comment.html", method = RequestMethod.GET)
	  public @ResponseBody String addComment(@RequestParam int item_id,@RequestParam String desc,HttpSession session){
		HTMLWriter htmlwriter=new HTMLWriter();
		String result="";
		CommentModel cmodel=new CommentModel();
		DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss a");
		DateFormat showFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
		//get current date time with Date()
		Date date = new Date();
		String curDate=dateFormat.format(date);
		/* Add new comment here */
		cmodel.InsertComment(item_id,desc,Integer.parseInt(session.getAttribute("user_id").toString()),curDate);
		int com_id=cmodel.getMaxIdbyItemId(item_id);
		//int com_id=9;
		String removeme="&nbsp;&nbsp;<label class=\"commentlink\" onclick=\"delete_comment.html?com_id="+com_id+"&wall_id="+com_id+"\">Remove</label>";
		result+="<p class=\"comment\" align=\"justify\">";
		result+="<label class=\"userpost\">"+session.getAttribute("user_name")+"&nbsp;</label>";
		result+=htmlwriter.escapeHTML(desc);
		result+="<br><br><label class=\"eventtext\">"+showFormat.format(date)+"</label>"+removeme+"";
		result+="</p>";
		
	    return result;
	  }
	
	@RequestMapping(value="view_comments.html", method = RequestMethod.GET)
	  public @ResponseBody String viewComments(@RequestParam int item_id) throws SQLException {
		String result="";
		HTMLWriter htmlwriter=new HTMLWriter();
		CommentModel cmodel=new CommentModel();
		ResultSet rstcom=cmodel.SelectComment(item_id);
		ResultSet rstuser=null;
		String username="";
		/* Loop all comment in a current item */
		while(rstcom.next()){
			rstuser=cmodel.SelectUser(rstcom.getInt("USER_POST"));
			while(rstuser.next()){
				username=rstuser.getString("USER_NAME");
			}
			result+="<p align=\"left\" style=\"font-size:11px;background-color: #CCC; padding: 10px;\">";
			result+="<b style=\"color: #333;\"><i>"+username+":</i>&nbsp;</b>";
			result+=htmlwriter.escapeHTML(rstcom.getString("COMMENT_DESC"));
			result+="<br><br><span style=\"color: #666; font-size: 10px;\">Post on:<span style=\"color: #222;\">"+rstcom.getString("DATE_POST")+"</span></span>";
			result+="</p>";
		}
	    return result;
	  }
	
	// RESULTSET TO ARRAYLIST
	   public ArrayList resultSetToArrayList(ResultSet rs) throws SQLException{
		    ResultSetMetaData md = rs.getMetaData();
		    int columns = md.getColumnCount();
		    ArrayList results = new ArrayList();
		    while (rs.next()){
		    HashMap row = new HashMap();
		    results.add(row);
			    for(int i=1; i<=columns; i++){
			    row.put(md.getColumnName(i),rs.getObject(i));
			    }
		    }
		    return results;

	    }
}